package com.ctg.payroll2.service.empadmin.Impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.ctg.payroll2.bean.EmployeeInfo;
import com.ctg.payroll2.bean.po.CsAccount;
import com.ctg.payroll2.bean.po.CsEmpAccount;
import com.ctg.payroll2.bean.po.CsOrgEmp;
import com.ctg.payroll2.bean.po.CsOrgchart;
import com.ctg.payroll2.bean.po.CsPositionEmp;
import com.ctg.payroll2.bean.po.PbEmpAccfundcard;
import com.ctg.payroll2.bean.po.PbEmpBankCard;
import com.ctg.payroll2.bean.po.PbEmpSocCard;
import com.ctg.payroll2.bean.po.PbEmployee;
import com.ctg.payroll2.bean.po.SysUser;
import com.ctg.payroll2.dao.cusadmin.CsAccountDAO;
import com.ctg.payroll2.dao.cusadmin.CsOrgEmpDAO;
import com.ctg.payroll2.dao.cusadmin.ICsOrgchartDAO;
import com.ctg.payroll2.dao.empadmin.CsPositionEmpDAO;
import com.ctg.payroll2.dao.empadmin.EmpAdminIndexDao;
import com.ctg.payroll2.dao.empadmin.PbEmpAccfundcardDAO;
import com.ctg.payroll2.dao.empadmin.PbEmpBankCardDAO;
import com.ctg.payroll2.dao.empadmin.PbEmpSocCardDAO;
import com.ctg.payroll2.service.empadmin.EmpAdminIndexService;
import com.ctg.platform.core.security.SpringSecurityManager;
import com.ctg.platform.core.security.Exception.SecurityException;
import com.ctg.platform.core.security.entity.Account;
import com.ctg.platform.orm.ibatis.IbatisEntityDao;
import com.ctg.platform.util.Page;
import com.ctg.platform.util.Parse;

public class EmpAdminIndexServiceImpl implements EmpAdminIndexService {

	private EmpAdminIndexDao empAdminIndexDao;

	private ICsOrgchartDAO csOrgchartDAO;
	
	private CsAccountDAO csAccountDAO;

	private PbEmpAccfundcardDAO pbEmpAccfundcardDAO;

	private PbEmpSocCardDAO pbEmpSocCardDAO;

	private PbEmpBankCardDAO pbEmpBankCardDAO;

	private CsOrgEmpDAO csOrgEmpDAO;

	private CsPositionEmpDAO csPositionEmpDAO;

	private SpringSecurityManager springSecurityManager;
	
	public CsAccountDAO getCsAccountDAO() {
		return csAccountDAO;
	}

	public void setCsAccountDAO(CsAccountDAO csAccountDAO) {
		this.csAccountDAO = csAccountDAO;
	}

	public SpringSecurityManager getSpringSecurityManager() {
		return springSecurityManager;
	}

	public void setSpringSecurityManager(
			SpringSecurityManager springSecurityManager) {
		this.springSecurityManager = springSecurityManager;
	}

	public ICsOrgchartDAO getCsOrgchartDAO() {
		return csOrgchartDAO;
	}

	public void setCsOrgchartDAO(ICsOrgchartDAO csOrgchartDAO) {
		this.csOrgchartDAO = csOrgchartDAO;
	}

	public CsPositionEmpDAO getCsPositionEmpDAO() {
		return csPositionEmpDAO;
	}

	public void setCsPositionEmpDAO(CsPositionEmpDAO csPositionEmpDAO) {
		this.csPositionEmpDAO = csPositionEmpDAO;
	}

	public PbEmpBankCardDAO getPbEmpBankCardDAO() {
		return pbEmpBankCardDAO;
	}

	public void setPbEmpBankCardDAO(PbEmpBankCardDAO pbEmpBankCardDAO) {
		this.pbEmpBankCardDAO = pbEmpBankCardDAO;
	}

	public CsOrgEmpDAO getCsOrgEmpDAO() {
		return csOrgEmpDAO;
	}

	public void setCsOrgEmpDAO(CsOrgEmpDAO csOrgEmpDAO) {
		this.csOrgEmpDAO = csOrgEmpDAO;
	}

	public EmpAdminIndexDao getEmpAdminIndexDao() {
		return empAdminIndexDao;
	}

	public void setEmpAdminIndexDao(EmpAdminIndexDao empAdminIndexDao) {
		this.empAdminIndexDao = empAdminIndexDao;
	}

	private IbatisEntityDao ibatisEntityDao;

	public IbatisEntityDao getIbatisEntityDao() {
		return ibatisEntityDao;
	}

	public void setIbatisEntityDao(IbatisEntityDao ibatisEntityDao) {
		this.ibatisEntityDao = ibatisEntityDao;
	}

	public PbEmpAccfundcardDAO getPbEmpAccfundcardDAO() {
		return pbEmpAccfundcardDAO;
	}

	public void setPbEmpAccfundcardDAO(PbEmpAccfundcardDAO pbEmpAccfundcardDAO) {
		this.pbEmpAccfundcardDAO = pbEmpAccfundcardDAO;
	}

	public PbEmpSocCardDAO getPbEmpSocCardDAO() {
		return pbEmpSocCardDAO;
	}

	public void setPbEmpSocCardDAO(PbEmpSocCardDAO pbEmpSocCardDAO) {
		this.pbEmpSocCardDAO = pbEmpSocCardDAO;
	}

	public Page getAllEmpAdminByPaging(String company_code, String emp_cs_code,
			String name, Integer is_valid, Integer out_jobdate,
			Integer departId, String start_date, String end_date, int start,
			int limit) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("company_code", company_code);
		if (emp_cs_code != null) {
			parameters.put("emp_cs_code", emp_cs_code);
		}
		if (name != null) {
			parameters.put("name", name);
		}
		if (is_valid != null) {
			parameters.put("is_valid", is_valid);
		}
		if (out_jobdate != null) {
			parameters.put("out_jobdate", out_jobdate);
		}
		if (departId != null) {
			parameters.put("orgchart_id", departId);
		}
		if (start_date != null) {
			parameters.put("start_date", start_date);
		}
		if (end_date != null) {

			parameters.put("end_date", end_date);
		}
		return empAdminIndexDao.pagedQuery(parameters, start, limit);
	}

	public void deleteEmployee(List data) throws SQLException {
		empAdminIndexDao.delete(data);
	}

	// ----------------------------用户权限分配开始----------------------------------------

	public void insertCsEmpAccount(Account acc, SysUser sysUser,
			String[] roleIds, CsEmpAccount csEmpAccount,String name) throws SQLException,
			SecurityException {
		Account account = springSecurityManager.createSysAccountAndGet(acc,
				sysUser);
		if (springSecurityManager.assignRoleForAccount(account, roleIds,
				sysUser)) {
			CsAccount csAccount=new CsAccount();
			csAccount.setCompany_code(sysUser.getCompanyCode());
			csAccount.setUser_id(account.getId());
			csAccount.setDisplay_name(name);
			csAccount.setCreator_id(sysUser.getEmployeeId());
			csAccount.setCreate_code(sysUser.getLoginId());
			csAccount.setCreator_ip(sysUser.getLoginIP());
			csAccount.setModifier_id(sysUser.getEmployeeId());
			csAccount.setModifier_code(sysUser.getLoginId());
			csAccount.setModifier_ip(sysUser.getLoginIP());
			csEmpAccount.setLogin_code(account.getId());
			csAccountDAO.insert(csAccount);
			empAdminIndexDao.insertempRoll(csEmpAccount);
		}
	}

	public CsEmpAccount queryEmproll(Integer empId) throws SQLException {
		return empAdminIndexDao.queryEmpRoll(empId);
	}

	// ----------------------------用户权限分配结束----------------------------------------

	public void saveEmployeeInfo(String company_code, String baseInfo,
			String socialSecurityNumber, String bankCardNumber)
			throws SQLException {
		Integer id = null;
		//System.out.println(baseInfo);
		//System.out.println(socialSecurityNumber);
		//System.out.println(bankCardNumber);
		// 保存基本信息
		id = saveEmployeeBaseInfo(company_code, baseInfo);
		// 保存社保账号
		saveEmpSocialSecurityNumber(id, socialSecurityNumber);
		// 保存公积金账号
		saveEmployeeSurplusAccount(id, socialSecurityNumber);
		// 保存银行账号
		saveBankCardNumber(id, bankCardNumber);

	}

	public EmployeeInfo getEmployeeInfo(Integer employee_id)
			throws SQLException {
		EmployeeInfo info = new EmployeeInfo();
		info.setPbEmployee(empAdminIndexDao.findByPrimaryKey(employee_id));
		info.setCsOrgEmp(csOrgEmpDAO.findByPrimaryKey(employee_id));
		info.setCsPositionEmp(csPositionEmpDAO.findByPrimaryKey(employee_id));
		info.setPbEmpAccfundcard(pbEmpAccfundcardDAO
				.findByPrimaryKey(employee_id));
		info.setPbEmpSocCard(pbEmpSocCardDAO.findByPrimaryKey(employee_id));
		info.setCards(pbEmpBankCardDAO.queryForList(".selectByEmployeeId",
				employee_id));
		if (info.getCsOrgEmp() != null) {
			info.setDepartmentName(getDepartmentName(info.getCsOrgEmp()
					.getOrgchart_id()));
		}
		return info;
	}

	/***************************************************************************
	 * public static void main(String[] args) { String json =
	 * "{\"emp_code\":\"\",\"emp_name\":\"\",\"birthday\":\"\",\"id_card_type\":\"\",\"gender\":\"\",\"nationality\":\"\",\"id_card_num\":\"\",\"resident_address\":\"\",\"address\":\"\",\"postcode\":\"\",\"resident_type\":\"\",\"marriage_status\":\"\",\"contact_tel1\":\"\",\"contact_tel3\":\"\",\"education_level\":\"\",\"email\":\"\",\"contact_tel2\":\"\",\"position\":\"\",\"join_date\":\"\",\"in_jobdate\":\"\",\"department\":\"\",\"service_start\":\"\",\"out_jobdate\":\"\"}";
	 * JSONObject employeeBaseInfoJSON = JSONObject.fromObject(json); Map p =
	 * new HashMap();
	 * 
	 * Iterator items = employeeBaseInfoJSON.entrySet().iterator(); while
	 * (items.hasNext()) { String o = items.next().toString(); o=o.substring(0,
	 * o.length()-1);
	 * System.out.println("tabPanel.findById('baseInfoPanelForm').findById('" +
	 * o + "').setValue(baseInfoJSON." + o + ");"); } }
	 **************************************************************************/

	/**
	 * 保存雇员基本信息
	 * 
	 * @param baseInfo
	 *            格式为："baseInfoPanelForm":{"emp_code":"","emp_name":"","birthday":"","id_card_type":"","gender":"","nationality":"",
	 *            "id_card_num":"","resident_address":"","address":"","postcode":"","resident_type":"",
	 *            "marriage_status":"","contact_tel1":"","contact_tel3":"","education_level":"","email":"","contact_tel2":"",
	 *            "position":"","join_date":"","in_jobdate":"","department":"","service_start":"","out_jobdate":""}
	 * 
	 * @return 雇员标识
	 * @throws SQLException
	 */
	private Integer saveEmployeeBaseInfo(String company_code, String baseInfo)
			throws SQLException {
		JSONObject employeeBaseInfoJSON = null;
		Map<String, Object> parameters = null;

		employeeBaseInfoJSON = JSONObject.fromObject("{" + baseInfo + "}")
				.getJSONObject("baseInfoPanelForm");

		PbEmployee employee = new PbEmployee();
		employee.setCompany_code(company_code);
		employee.setEmployee_id(Parse.toInteger(employeeBaseInfoJSON
				.getString("employee_id")));
		employee.setEmp_cs_code(Parse.toString(employeeBaseInfoJSON
				.getString("emp_code"), false));
		employee.setName(Parse.toString(employeeBaseInfoJSON
				.getString("emp_name"), false));
		employee.setBirthday(Parse.toDate(employeeBaseInfoJSON
				.getString("birthday"), "yyyy-MM-dd"));
		employee.setId_card_type(Parse.toInteger(employeeBaseInfoJSON
				.getString("id_card_type")));
		employee.setGender(Parse.toInteger(employeeBaseInfoJSON
				.getString("gender")));
		employee.setNationality(Parse.toString(employeeBaseInfoJSON
				.getString("nationality"), true));
		employee.setId_card_num(Parse.toString(employeeBaseInfoJSON
				.getString("id_card_num"), true));
		employee.setResident_type(Parse.toInteger(employeeBaseInfoJSON
				.getString("resident_type")));
		employee.setResident_address(Parse.toString(employeeBaseInfoJSON
				.getString("resident_address"), true));
		employee.setAddress(Parse.toString(employeeBaseInfoJSON
				.getString("address"), true));
		employee.setPostcode(Parse.toString(employeeBaseInfoJSON
				.getString("postcode"), true));
		employee.setMarriage_status(Parse.toInteger(employeeBaseInfoJSON
				.getString("marriage_status")));
		employee.setContact_tel1(Parse.toString(employeeBaseInfoJSON
				.getString("contact_tel1"), true));
		employee.setContact_tel2(Parse.toString(employeeBaseInfoJSON
				.getString("contact_tel2"), true));
		employee.setContact_tel3(Parse.toString(employeeBaseInfoJSON
				.getString("contact_tel3"), true));
		employee.setEducation_level(Parse.toInteger(employeeBaseInfoJSON
				.getString("education_level")));
		employee.setEmail(Parse.toString(employeeBaseInfoJSON
				.getString("email"), true));
		employee.setBase_pay_pro(Parse.toDouble(employeeBaseInfoJSON
				.getString("base_pay_pro")));
		employee.setBase_pay(Parse.toDouble(employeeBaseInfoJSON
				.getString("base_pay")));
		employee.setContract_type(Parse.toInteger(employeeBaseInfoJSON
				.getString("contract_type")));
		employee.setPolity(Parse.toInteger(employeeBaseInfoJSON
				.getString("polity")));
		employee.setHealth_status(Parse.toInteger(employeeBaseInfoJSON
				.getString("health_status")));
		employee.setJoin_date(Parse.toDate(employeeBaseInfoJSON
				.getString("join_date"), "yyyy-MM-dd"));
		employee.setIn_jobdate(Parse.toDate(employeeBaseInfoJSON
				.getString("in_jobdate"), "yyyy-MM-dd"));
		employee.setOut_jobdate(Parse.toDate(employeeBaseInfoJSON
				.getString("out_jobdate"), "yyyy-MM-dd"));
		employee.setService_start(Parse.toInteger(employeeBaseInfoJSON
				.getString("service_start")));
		employee.setIs_valid(true);
		employee.setIs_injob(new Integer(0));

		if (employee.getEmployee_id() == null) {
			empAdminIndexDao.insert(employee);
		} else {
			empAdminIndexDao.update(employee);
		}

		saveEmpDepartment(company_code, employee.getEmployee_id(), Parse
				.toInteger(employeeBaseInfoJSON.getString("department")));
		// saveEmpPosition(company_code,employee.getEmployee_id(),Parse.toString(employeeBaseInfoJSON.getString("department"),
		// true));

		return employee.getEmployee_id();
	}

	/**
	 * 保存雇员的部门信息
	 * 
	 * @param company_code
	 *            公司标识
	 * @param employee_id
	 *            员工标示
	 * @param department_id
	 *            部门标识
	 * @throws SQLException
	 */
	private void saveEmpDepartment(String company_code, Integer employee_id,
			Integer department_id) throws SQLException {
		CsOrgEmp orgEmp = null;
		if (employee_id == null) {
			return;
		}
		orgEmp = csOrgEmpDAO.findByPrimaryKey(employee_id);
		if (orgEmp == null) {
			if (department_id == null) {
				return;
			}
			orgEmp = new CsOrgEmp();
			orgEmp.setCompany_code(company_code);
			orgEmp.setEmployee_id(employee_id);
			orgEmp.setOrgchart_id(department_id);
			orgEmp.setIs_major(new Integer(0));
		} else {
			orgEmp.setOrgchart_id(department_id);
			csOrgEmpDAO.update(orgEmp);
		}
	}

	/**
	 * 保存雇员的岗位信息
	 * 
	 * @param company_code
	 * @param employee_id
	 * @param position
	 * @throws SQLException
	 */
	private void saveEmpPosition(String company_code, Integer employee_id,
			String position) throws SQLException {
		CsPositionEmp posEmp = null;
		if (employee_id == null) {
			return;
		}
		posEmp = csPositionEmpDAO.findByPrimaryKey(employee_id);
		if (posEmp == null) {
			if (position == null) {
				return;
			}
			posEmp = new CsPositionEmp();
			posEmp.setCompany_code(company_code);
			posEmp.setEmployee_id(employee_id);
			posEmp.setPosition_code(position);
			csPositionEmpDAO.insert(posEmp);
		} else {
			posEmp.setPosition_code(position);
			csPositionEmpDAO.update(posEmp);
		}
	}

	/**
	 * 保存雇员的社会保证卡号信息
	 * 
	 * @param employee_id
	 *            员工标识
	 * @param socialSecurityNumber
	 *            社会保障号
	 *            格式为："socialSecurityNumberPanel":{"socialSecurityNumber":"1234567890";"surplusAccount":"1234567890"}
	 * @throws SQLException
	 */
	private void saveEmpSocialSecurityNumber(Integer employee_id,
			String socialSecurityNumber) throws SQLException {
		JSONObject socialSecurityNumberJSON = null;
		Map<String, Object> parameters = null;

		if (employee_id == null || socialSecurityNumber == null
				|| socialSecurityNumber.equals("")) {
			return;
		}

		socialSecurityNumberJSON = JSONObject.fromObject(
				"{" + socialSecurityNumber + "}").getJSONObject(
				"socialSecurityNumberPanel");

		// 社保账户
		if (socialSecurityNumberJSON != null
				&& socialSecurityNumberJSON.getString("socialSecurityNumber") != null) {
			// System.out.println("step1");
			parameters = new HashMap<String, Object>();
			parameters.put("employee_id", employee_id);

			if (pbEmpSocCardDAO.findByPrimaryKey(employee_id) != null) {
				parameters.put("soccard_code", Parse.toString(
						socialSecurityNumberJSON
								.getString("socialSecurityNumber"), true));
				pbEmpSocCardDAO.update(".update", parameters);
			} else {
				PbEmpSocCard socCard = new PbEmpSocCard();
				socCard.setEffective_date(null);
				socCard.setEmployee_id(employee_id);
				socCard.setIs_valid(Boolean.TRUE);
				socCard.setSoccard_code(Parse.toString(socialSecurityNumberJSON
						.getString("socialSecurityNumber"), true));
				pbEmpSocCardDAO.insert(socCard);
			}
		}
	}

	/**
	 * 保存雇员公积金账户
	 * 
	 * @param employee_id
	 *            员工标识
	 * @param socialSecurityNumber
	 * @throws SQLException
	 */
	private void saveEmployeeSurplusAccount(Integer employee_id,
			String socialSecurityNumber) throws SQLException {
		JSONObject socialSecurityNumberJSON = null;
		Map<String, Object> parameters = null;

		if (employee_id == null || socialSecurityNumber == null
				|| socialSecurityNumber.equals("")) {
			return;
		}

		socialSecurityNumberJSON = JSONObject.fromObject(
				"{" + socialSecurityNumber + "}").getJSONObject(
				"socialSecurityNumberPanel");

		// 公积金账户
		if (socialSecurityNumberJSON != null
				&& socialSecurityNumberJSON.getString("surplusAccount") != null) {
			parameters = new HashMap<String, Object>();
			parameters.put("employee_id", employee_id);

			if (pbEmpAccfundcardDAO.findByPrimaryKey(employee_id) != null) {
				parameters.put("accfundcard_code", Parse.toString(
						socialSecurityNumberJSON.getString("surplusAccount"),
						false));
				pbEmpAccfundcardDAO.update(".update", parameters);
			} else {
				PbEmpAccfundcard accfundcard = new PbEmpAccfundcard();
				accfundcard.setEffective_date(null);
				accfundcard.setEmployee_id(employee_id);
				accfundcard.setIs_valid(Boolean.TRUE);
				accfundcard.setAccfundcard_code(Parse.toString(
						socialSecurityNumberJSON.getString("surplusAccount"),
						false));
				pbEmpAccfundcardDAO.insert(accfundcard);
			}
		}
	}

	/**
	 * 保存银行账号
	 * 
	 * @param id
	 *            雇员标识
	 * @param bankCardNumber
	 * @throws SQLException
	 */
	private void saveBankCardNumber(Integer id, String bankCardNumber)
			throws SQLException {
		// System.out.println(bankCardNumber);
		JSONObject bankCardJSON = null;

		if (id == null || bankCardNumber == null) {
			return;
		}
		bankCardJSON = JSONObject.fromObject("{" + bankCardNumber + "}");

		if (bankCardJSON.get("deleted") instanceof JSONArray) {
			Iterator<JSONObject> deletedItems = bankCardJSON.getJSONArray(
					"deleted").iterator();
			while (deletedItems.hasNext()) {
				Integer card_id = Parse.toInteger(deletedItems.next()
						.getString("bankcard_id"));
				pbEmpBankCardDAO.deleteByPrimaryKey(card_id);
			}
		}

		if (bankCardJSON.get("modified") instanceof JSONArray) {
			Iterator<JSONObject> modifiedItems = bankCardJSON.getJSONArray(
					"modified").iterator();
			while (modifiedItems.hasNext()) {
				JSONObject item = modifiedItems.next();

				PbEmpBankCard card = new PbEmpBankCard();
				card.setBank_code(Parse.toString(item.getString("bank_code"),
						false));
				card.setBank_id(Parse
						.toString(item.getString("bank_id"), false));
				card.setBank_name(Parse.toString(item.getString("bank_name"),
						false));
				// card.setBank_type(Parse.toInteger(item.getString("bank_type")));
				card.setBankcard_id(Parse.toInteger(item
						.getString("bankcard_id")));

				if (card.getBankcard_id() == null) {
					card.setEmployee_code(id);
					card.setIs_valid(true);
					pbEmpBankCardDAO.insert(card);
				} else {
					pbEmpBankCardDAO.update(card);
				}
			}
		}
	}

	private String getDepartmentName(Integer id) throws SQLException {
		CsOrgchart chart = csOrgchartDAO.findByPrimaryKey(id);
		if (chart != null) {
			return chart.getOrgchart_name();
		}
		return null;
	}


}
